package download;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MyDownload {
	
    private URL url; // download URL
    private int size; // size of download in bytes
    private int downloaded; // number of bytes downloaded
    private int status; // current status of download
    File file = null;
	
	   // Download file.
    public void run() {
        InputStream stream = null;
        BufferedOutputStream outputStream = null;
        
        try {
            // Open connection to URL.
            HttpURLConnection connection =
                    (HttpURLConnection) url.openConnection();
            
            // Specify what portion of file to download.
            connection.setRequestProperty("Range",
                    "bytes=" + downloaded + "-");
            
            // Connect to server.
            connection.connect();
            

            
            // Check for valid content length.
            int contentLength = connection.getContentLength();

            
      /* Set the size for this download if it
         hasn't been already set. */
            if (size == -1) {
                size = contentLength;
            }
            
            // Open file and seek to the end of it.
            file = new File("C:/Temp", "Hello.txt");
            outputStream = new BufferedOutputStream(
            	new FileOutputStream(file));
            stream = connection.getInputStream();
            while (status == DOWNLOADING) {
        /* Size buffer according to how much of the
           file is left to download. */
                byte buffer[];
                if (size - downloaded > MAX_BUFFER_SIZE) {
                    buffer = new byte[MAX_BUFFER_SIZE];
                } else {
                    buffer = new byte[size - downloaded];
                }
                
                // Read from server into buffer.
                int read = stream.read(buffer);
                if (read == -1)
                    break;
                
                // Write buffer to file.
                outputStream.write(buffer, 0, read);
                downloaded += read;

            }
            
        } catch (Exception e) {
            error();
        } finally {
            // Close file.
            if (file != null) {
                try {
                	outputStream.close();
                } catch (Exception e) {}
            }
            
            // Close connection to server.
            if (stream != null) {
                try {
                    stream.close();
    				System.out.println(file.getAbsolutePath());
                } catch (Exception e) {}
            }
        }
    }
}
